package net.apexes.commons.ormlite;

import com.j256.ormlite.dao.ObjectCache;
import com.j256.ormlite.field.DatabaseFieldConfig;
import com.j256.ormlite.field.FieldType;
import com.j256.ormlite.support.ConnectionSource;

import java.lang.reflect.Field;
import java.sql.SQLException;

/**
 * @author <a href=mailto:hedyn@foxmail.com>HeDYn</a>
 */
class UnreflectFieldType<T> extends FieldType {

    private final Table<T> table;
    final ColumnDatabaseFieldConfig columnConfig;

    public UnreflectFieldType(ConnectionSource connectionSource,
                              Table<T> table,
                              String tableName,
                              Field field,
                              DatabaseFieldConfig fieldConfig,
                              Class<?> parentClass) throws SQLException {
        super(connectionSource, tableName, field, fieldConfig, parentClass);
        this.table = table;
        if (fieldConfig instanceof ColumnDatabaseFieldConfig) {
            columnConfig = (ColumnDatabaseFieldConfig) fieldConfig;
        } else {
            columnConfig = null;
        }
    }

    @Override
    public void assignField(Object data, Object val, boolean parentObject, ObjectCache objectCache) throws SQLException {
        table.setupFieldValue((T) data, getFieldName(), val);
    }

    @Override
    public <FV> FV extractRawJavaFieldValue(Object object) throws SQLException {
        return (FV) table.getFieldValue((T) object, getFieldName());
    }
}
